<?php
/**
 * Created by PhpStorm.
 * User: xiaoqi
 * Date: 18-9-19
 * Time: 上午10:21
 */

namespace App\HttpController\Api;

use EasySwoole\Core\Http\AbstractInterface\Controller;
use EasySwoole\Core\Http\Message\Status;
use EasySwoole\Config;

abstract class AbstractBase extends Controller
{
    /**
     * 不定义index方法报404
     */
    function index()
    {
        // TODO: Implement index() method.
        $this->actionNotFound('index');
    }

    /**
     * 方法找不到
     * @param $action
     */
    protected function actionNotFound($action): void
    {
        $this->writeJson(Status::CODE_NOT_FOUND);
    }

    /**
     * 验证权限
     *
     * @param $action
     * @return bool|null
     */
    protected function onRequest($action): ?bool
    {
        $server = $this->request()->getServerParams();
        // 过滤登陆接口
        if ($server['request_uri'] === '/api/login') {
            return true;
        } else {
            $path = $server['request_uri'];
            $secret = Config::getInstance()->getConf('SECRET');
            $data = $this->request()->getHeaders();
            if (isset($data['authorization'])) {
                $token = $data['authorization'];
                $auth_data = jwt_decode((string)$token[0], $secret['jwt'], ['algorithm' => 'HS256']);
                $user = \App\Model\User::find((int)$auth_data['uid']);
                if ($user) {
                    $this->request()->user = $user;
                    return true;
                } else {
                    $this->request()->user = null;
                    $this->error('该用户不存在');
                    return false;
                }
            } else {
                $this->error('用户未登陆');
                return false;
            }
        }
    }

    /**
     * 用来返回错误信息（json）
     * @param $code
     * @param $message
     * @return bool
     */
    protected function error($message, $status = 200){
        if(!$this->response()->isEndResponse()){
            $data = Array(
                "ret"   => 0 ,
                "data"  => "",
                "msg"   => $message
            );
            $this->response()->write(json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
            $this->response()->withHeader('Content-type','application/json;charset=utf-8');
            $this->response()->withStatus($status);
            return true;
        }else{
            trigger_error("response has end");
            return false;
        }
    }

    /*
     * 用来返回成功信息（json）
     */
    protected function success($result = '', $status = 200){
        if(!$this->response()->isEndResponse()){
            $data = Array(
                "ret"     => 1,
                "data"    => $result,
                "msg"     => ''
            );
            $this->response()->write(json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
            $this->response()->withHeader('Content-type','application/json;charset=utf-8');
            $this->response()->withStatus($status);
            return true;
        }else{
            trigger_error("response has end");
            return false;
        }
    }

    /**
     * 获取第一个验证错误信息
     *
     * @param array $errors
     * @return mixed|string
     */
    protected function valideErrorFirst($errors = [])
    {
        $errorText = '';
        foreach ($errors as $key => $error)
        {
            $errorText = $error;
            break;
        }
        return $errorText;
    }
}